<?php
    include '../lib/confs/Conf.php';    
    //Update leave entitled day for employee who work for S3 over 5 year
    $empIds = get(5);
    $id = array();
    while ($empId = mysql_fetch_array($empIds)) {
        $id[] = $empId['emp_number'];
        if(!check($empId['emp_number'])){
            add($empId['emp_number']);
        }
    }
    if(count($id)>0){
        update(implode(',',$id));
    }
    
    //Update leave entitled day for employee who work for S3 over 10 year
    $empIds = get(10);
    $id = array();
    while ($empId = mysql_fetch_array($empIds)) {
        $id[] = $empId['emp_number'];
        if(!check($empId['emp_number'])){
            add($empId['emp_number']);
        }
    }
    if(count($id)>0){
        update(implode(',',$id));
    }
    echo "Update successful";
    exit;
    
    function check($employeeId) {
        $query = "SELECT COUNT(*) FROM `hs_hr_employee_leave_quota` WHERE `year` = YEAR(CURDATE()) AND `leave_type_id` = 'LTY001' AND `employee_id` = '" . $employeeId . "'";
        $result = query($query);
        $count = mysql_fetch_row($result);
        if ($count[0] > 0) {
            return true;
        }
        return false;
    }
    
    function update($employeeId) {        
        $query = "UPDATE hs_hr_employee_leave_quota SET leave_brought_forward = leave_brought_forward +1 WHERE leave_type_id ='LTY001' AND year = YEAR(CURDATE()) AND `employee_id` IN (" . $employeeId . ")";       
        return  query($query);
    }
    
    function add($employeeId) {
        $query = "INSERT INTO hs_hr_employee_leave_quota VALUES (YEAR(CURDATE()),'LTY001',".$employeeId.")";        
        return  query($query);
    }
    
    function get($year) {
        $query = "SELECT emp_number FROM hs_hr_employee WHERE floor(datediff(curdate(),joined_date) / 365) >= ".$year." AND emp_status != 'EST000'";
        return query($query);
    }
    
    function query($query) {
        $conf = new Conf();    
        $user=$conf->dbuser;
        $password=$conf->dbpass;
        $database=$conf->dbname;
        $server=$conf->dbhost;
	$con = mysql_connect($server, $user, $password);
        if (!$con) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die("Unable to select database " . $database . ".");      
        $result = mysql_query($query) or die(mysql_error());        
        mysql_close();
        return $result;
    }

?>
